//
//  df.m
//  里
//
//  Created by 众里寻TA on 14-11-25.
//  Copyright (c) 2014年 李 剣. All rights reserved.
//

#import "df.h"
#import <objc/runtime.h> 
#import "JTCSMSingle.h"
#import <CommonCrypto/CommonDigest.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "JTCSM.h"
#import "LoginViewController.h"
#include <ifaddrs.h>
#include <arpa/inet.h>

typedef NS_ENUM(NSInteger, HYBJSONModelDataType) {
    kHYBJSONModelDataTypeObject    = 0,
    kHYBJSONModelDataTypeBOOL      = 1,
    kHYBJSONModelDataTypeInteger   = 2,
    kHYBJSONModelDataTypeFloat     = 3,
    kHYBJSONModelDataTypeDouble    = 4,
    kHYBJSONModelDataTypeLong      = 5,
};
@implementation df
#pragma mark - Custom Method


/*!
 * @brief 把字典转换成模型，模型类名为className
 * @param dict 字典对象
 * @param className 类名
 * @return 返回数据模型对象
 */
+ (id)modelWithDict:(NSDictionary *)dict className:(NSString *)className {
    if (dict == nil || className == nil || className.length == 0) {
        return nil;
    }
    
    id model = [[NSClassFromString(className) alloc]init];
    
    // 取得类对象
    id classObject = objc_getClass([className UTF8String]);
    
    unsigned int count = 2;
    objc_property_t *properties = class_copyPropertyList(classObject, &count);
    Ivar *ivars = class_copyIvarList(classObject, nil);
    for (int i = 0; i < count; i ++) {
        // 取得成员名
        NSString *memberName = [NSString stringWithUTF8String:ivar_getName(ivars[i])];
        const char *type = ivar_getTypeEncoding(ivars[i]);
        NSString *dataType =  [NSString stringWithCString:type encoding:NSUTF8StringEncoding];
        
        HYBJSONModelDataType namer = kHYBJSONModelDataTypeObject;
        
        if ([dataType hasPrefix:@"c"]) {
            namer = kHYBJSONModelDataTypeBOOL;// BOOL
        } else if ([dataType hasPrefix:@"i"]) {
            namer = kHYBJSONModelDataTypeInteger;// int
        } else if ([dataType hasPrefix:@"f"]) {
            namer = kHYBJSONModelDataTypeFloat;// float
        } else if ([dataType hasPrefix:@"d"]) {
            namer = kHYBJSONModelDataTypeDouble; // double
        } else if ([dataType hasPrefix:@"l"])  {
            namer = kHYBJSONModelDataTypeLong;// long
        }
        
        for (int j = 0; j < count; j++) {
            objc_property_t property = properties[j];
            NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)
                                                              encoding:NSUTF8StringEncoding];
            NSRange range = [memberName rangeOfString:propertyName];
            
            if (range.location == NSNotFound) {
                continue;
            } else {
                id propertyValue = [dict objectForKey:propertyName];
                
                switch (namer) {
                    case kHYBJSONModelDataTypeBOOL: {
                        BOOL temp = [[NSString stringWithFormat:@"%@", propertyValue] boolValue];
                        propertyValue = [NSNumber numberWithBool:temp];
                    }
                        break;
                    case kHYBJSONModelDataTypeInteger: {
                        int temp = [[NSString stringWithFormat:@"%@", propertyValue] intValue];
                        propertyValue = [NSNumber numberWithInt:temp];
                    }
                        break;
                    case kHYBJSONModelDataTypeFloat: {
                        float temp = [[NSString stringWithFormat:@"%@", propertyValue] floatValue];
                        propertyValue = [NSNumber numberWithFloat:temp];
                    }
                        break;
                    case kHYBJSONModelDataTypeDouble: {
                        double temp = [[NSString stringWithFormat:@"%@", propertyValue] doubleValue];
                        propertyValue = [NSNumber numberWithDouble:temp];
                    }
                        break;
                    case kHYBJSONModelDataTypeLong: {
                        long long temp = [[NSString stringWithFormat:@"%@",propertyValue] longLongValue];
                        propertyValue = [NSNumber numberWithLongLong:temp];
                    }
                        break;
                        
                    default:
                        break;
                }
                
                [model setValue:propertyValue forKey:memberName];
                break;
            }
        }
    }
    return model;
}



/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    jsonString = [jsonString stringByReplacingOccurrencesOfString : @"renderReverse&&renderReverse(" withString : @"" ];
    jsonString = [jsonString stringByReplacingOccurrencesOfString : @")" withString : @"" ];
    jsonString = [jsonString stringByReplacingOccurrencesOfString : @"\r\n" withString : @"" ];
    
    jsonString = [jsonString stringByReplacingOccurrencesOfString : @"\n" withString : @"" ];
    
    jsonString = [jsonString stringByReplacingOccurrencesOfString : @"\t" withString : @"" ];
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }
    return dic;
}

+(NSDictionary*)getObjectData:(id)obj

{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    unsigned int propsCount;
    
    objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
    
    for(int i = 0;i < propsCount; i++)
        
    {
        
        objc_property_t prop = props[i];
        NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
        id value = [obj valueForKey:propName];
        
        if(value== nil)
            
        {
            
            value = [NSNull null];
            
        }
        
        else
            
        {
            
            value = [self getObjectInternal:value];
            
        }
        
        [dic setObject:value forKey:propName];
        
    }
    
    return
    
    dic;
    
}
+ (id)getObjectInternal:(id)obj

{
    
    if([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]] || [obj isKindOfClass:[NSNull class]])
        
    {
        
        return obj;
        
    }
    
    
    
    if([obj isKindOfClass:[NSArray class]])
        
    {
        
        NSArray *objarr = obj;
        
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        
        for(int i = 0;i < objarr.count; i++)
            
        {
            [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
            
        }
        
        return arr;
        
    }
    
    
    
    if([obj isKindOfClass:[NSDictionary class]])
        
    {
        
        NSDictionary *objdic = obj;
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        
        for(NSString *key in objdic.allKeys)
            
        {
            
            [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];          
        }     
        
        return dic;
        
    } 
    
    return [self getObjectData:obj];
    
}

+(NSString *) converUrl:(NSString *)url{
    if (url.length>7) {
        if (![[url substringToIndex:7] isEqualToString:@"http://"]) {
            url=[NSString stringWithFormat:@"http://%@",url];
        }
    }
    return url;
}


//图片压缩
+(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(size);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage *)imageByScalingToSize:(CGSize)targetSize imagename:(UIImage *)image
{
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor < heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor < heightFactor) {
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        } else if (widthFactor > heightFactor) {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    // this is actually the interesting part:
    UIGraphicsBeginImageContext(targetSize);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    return newImage ;
}


+(CGFloat) getConfigByName:(NSString *)name defaultValue:(CGFloat)defaultValue{
    CGFloat value= 0;
    NSDictionary *dic=  [StorageUtil readFile:@"config.txt"];
    if(dic!=nil){
        value=  [[dic objectForKey:name] floatValue];
    }
    value=value>0?value:defaultValue;
    return value;
}

+(NSString *) getNumFromFileByName:(NSString *)filename name:(NSString *)name{
    NSDictionary *dic=  [StorageUtil readFile:filename];
    return  [dic objectForKey:name] ;
}

+(BOOL) hasPraised:(NSString *)chatname isClickPraised:(BOOL)isClickPraised{
   NSString * praisedValue= [StorageUtil readFileStr:@"praisedValue.txt"];
    if (praisedValue!=nil && ![praisedValue isEqualToString:@""]) {
        if ([praisedValue rangeOfString:chatname].location!=NSNotFound) {
            return  true;
        }
    }
    if (isClickPraised) {
    NSString *newValue=[praisedValue==nil?@"":praisedValue stringByAppendingString:chatname];
    [StorageUtil writeToFile:@"praisedValue.txt" data:newValue];
    }
    return false;
}


+ (CGRect)getheightWithContext:(NSString *)context label:(UILabel *)label{
    
    return [context boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-55, 10000) options: NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName, nil] context:nil];
}
#pragma mark 根据size截取图片中间矩形区域的图片 这里的size是正方形
+(UIImage *)cutCenterImage:(UIImage *)image size:(CGSize)size{
    CGSize imageSize = image.size;
    CGRect rect;
    //根据图片的大小计算出图片中间矩形区域的位置与大小
    if (imageSize.width > imageSize.height) {
        float leftMargin = (imageSize.width - imageSize.height) * 0.5;
        rect = CGRectMake(leftMargin, 0, imageSize.height, imageSize.height);
    }else{
        float topMargin = (imageSize.height - imageSize.width) * 0.5;
        rect = CGRectMake(0, topMargin, imageSize.width, imageSize.width);
    }
    
    CGImageRef imageRef = image.CGImage;
    //截取中间区域矩形图片
    CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
    
    UIImage *tmp = [[UIImage alloc] initWithCGImage:imageRefRect];
    CGImageRelease(imageRefRect);
    
    UIGraphicsBeginImageContext(size);
    CGRect rectDraw = CGRectMake(0, 0, size.width, size.height);
    [tmp drawInRect:rectDraw];
    // 从当前context中创建一个改变大小后的图片
    tmp = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    return tmp;
}

// 设置视图的边框 圆角及 颜色
+(void)layerWithView:(UIView *)view radius:(CGFloat)cornerRadiu width:(CGFloat)borderWidth color:(UIColor *)borderColor{
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = cornerRadiu;
    view.layer.borderWidth = borderWidth;
    view.layer.borderColor = borderColor.CGColor;
}

//添加手势
+(UITapGestureRecognizer *)addTapGestureRecognizerWithTarget:(id)target action:(SEL)action andaddView:(UIView *)view{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:target action:action];
    [view addGestureRecognizer:tap];
    
    return tap;
    
}

//提示框
+(UIAlertView *)showAlertWithTitle:(NSString *)title message:(NSString *)message btn1:(NSString *)btn1 btn2:(NSString *)btn2 btn3:(NSString *)btn3 delegate:(id)object tag:(NSInteger)tag{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:object cancelButtonTitle:btn1 otherButtonTitles:btn2,btn3, nil];
    alert.tag = tag + KAlertVTag;
    alert.userInteractionEnabled = YES;    
    [alert show];
    return alert;
}

//获取数字键盘
+ (void)getKeyboardPodWithTextfield:(UITextField *)textfield isKeyboard:(BOOL)iskeyboard isSecureEntry:(BOOL)secureEntry{
    if (iskeyboard ) {
        textfield.keyboardType = UIKeyboardTypePhonePad;
    }
    if (secureEntry) {
        textfield.secureTextEntry = YES;
    }
}
+ (void)isRemoveTarbar:(BOOL)isremove{//发送通知移除Tarbar
    [JTCSMSingle shareSingle].isRemoveTarbar = isremove;
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"remonvTarBar" object:self];
}
+ (void)gotoTheFirstVC{
    
    NSLog(@"10");
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"gotoTheFirst" object:self];
}
//label自适应高度
+ (CGRect)labelHeightWithContent:(NSString *)content width:(CGFloat )width label:(UILabel *)label{
    
    CGRect rect=[content boundingRectWithSize:CGSizeMake(width, 100000) options: NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName, nil] context:nil];
    //有多少行可显示多少行
    label.numberOfLines=0;
    return rect;
}
//label自适应高度
+ (CGRect)labelHeightWithContent:(NSString *)content width:(CGFloat )width font:(float )font{
    
    CGRect rect=[content boundingRectWithSize:CGSizeMake(width, 100000) options: NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:font],NSFontAttributeName, nil] context:nil];

    return rect;
}

//label自适应宽度
+ (CGRect)labelHeightWithContent:(NSString *)content height:(CGFloat )height label:(UILabel *)label{
    
    CGRect rect=[content boundingRectWithSize:CGSizeMake(10000, height) options: NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName, nil] context:nil];
//    //有多少行可显示多少行
//    label.numberOfLines=0;
     return rect;
}

//label自适应宽度
+ (CGRect)labelHeightWithContent:(NSString *)content height:(CGFloat )height font:(CGFloat)font{
    
    CGRect rect=[content boundingRectWithSize:CGSizeMake(10000, height) options: NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:font],NSFontAttributeName, nil] context:nil];
    //    //有多少行可显示多少行
    //    label.numberOfLines=0;
    return rect;
}

//label自适应宽度
+ (CGRect)textfieldHeightWithContent:(NSString *)content height:(CGFloat )height textfield:(UITextField *)label{
    
    CGRect rect=[content boundingRectWithSize:CGSizeMake(10000, height) options: NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName, nil] context:nil];
    //    //有多少行可显示多少行
    //    label.numberOfLines=0;
    return rect;
}

//跳转到登陆页

+ (void)gotoLoginVC:(UINavigationController *)nav {
    
    [nav popToRootViewControllerAnimated:NO];
    LoginViewController*Vc = [[LoginViewController alloc]init];
    Vc.delegate =     [JTCSMSingle shareSingle].myappDelegate;
    UINavigationController *mynav = [[UINavigationController alloc]initWithRootViewController:Vc];
    [JTCSMSingle shareSingle].theWindow.rootViewController = mynav;
}

+(void)gotoMainViewController{
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"completePresentMainVC" object:self];

}

//菊花
+(UIActivityIndicatorView *)showWaiting:(UIView *)parent {
    
    int width = 32, height = 32;
    
    CGRect frame = [parent frame]; //[[UIScreen mainScreen] applicationFrame];
    int x = frame.size.width;
    int y = frame.size.height;
    CGFloat changesize = 10;
    frame = CGRectMake((x - width-changesize) / 2, (y - height-changesize) / 2, width+changesize, height+changesize);
    UIView *theV = [[UIView alloc] initWithFrame:frame];
    theV.backgroundColor = [UIColor clearColor];
    [df layerWithView:theV radius:4 width:0 color:nil];
    frame = CGRectMake((x - width) / 2, (y - height) / 2, width, height);
    UIActivityIndicatorView* progressInd = [[UIActivityIndicatorView alloc]initWithFrame:frame];
    progressInd.center = CGPointMake(theV.frame.size.width/2, theV.frame.size.height/2);
    [progressInd startAnimating];
    progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    
    //    frame = CGRectMake((x - 70)/2, (y - height) / 2 + height, 80, 20);
    //    UILabel *waitingLable = [[UILabel alloc] initWithFrame:frame];
    //    waitingLable.text = @"Loading...";
    //    waitingLable.textColor = [UIColor whiteColor];
    //    waitingLable.font = [UIFont systemFontOfSize:15];
    //    waitingLable.backgroundColor = [UIColor clearColor];
    
    frame =  CGRectMake(0, 0, x, y);
    UIView *theView = [[UIView alloc] initWithFrame:frame];
    theView.backgroundColor = [UIColor clearColor];
    
    
    [theV addSubview:progressInd];
    //    [theView addSubview:waitingLable];
    
    
    [theView setTag:945983458];
    [theView addSubview:theV];
    [parent addSubview:theView];
    [parent bringSubviewToFront:theView];
    
    //    [[XGTSingle shareSingle].rootView addSubview:theView];
    //    [progressInd insertSubview:theView atIndex:1];
    
    return progressInd;
}
//消除滚动轮指示器
+(void)hideWaiting:(UIView *)parent
{
    [[parent viewWithTag:945983458] removeFromSuperview];
}

//32位MD5加密方式
+ (NSString *)getMd5_32Bit_String:(NSString *)srcString{
    const char *cStr = [srcString UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    // CC_MD5( cStr, strlen(cStr), digest ); 这里的用法明显是错误的，但是不知道为什么依然可以在网络上得以流传。当srcString中包含空字符（\0）时
    CC_MD5( cStr, (CC_LONG)strlen(cStr), digest );
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [result appendFormat:@"%02x", digest[i]];
    
    return result;
}

+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha
{
    //删除字符串中的空格
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6)
    {
        return [UIColor clearColor];
    }
    // strip 0X if it appears
    //如果是0x开头的，那么截取字符串，字符串从索引为2的位置开始，一直到末尾
    if ([cString hasPrefix:@"0X"])
    {
        cString = [cString substringFromIndex:2];
    }
    //如果是#开头的，那么截取字符串，字符串从索引为1的位置开始，一直到末尾
    if ([cString hasPrefix:@"#"])
    {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6)
    {
        return [UIColor clearColor];
    }
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:alpha];
}

//设置不同字体颜色
+ (void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text];
    //设置字号
    [str addAttribute:NSFontAttributeName value:font range:range];
    //设置文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
    labell.attributedText = str;
}

//设置不同字体颜色
+ (void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange1:(NSRange)range1 AndRange2:(NSRange)range2 AndColor1:(UIColor *)vaColor1 AndColor2:(UIColor *)vaColor2{
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text];
    //设置字号
    [str addAttribute:NSFontAttributeName value:font range:range1];
    //设置文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor1 range:range1];
    //设置字号
    [str addAttribute:NSFontAttributeName value:font range:range2];
    //设置文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor2 range:range2];
    labell.attributedText = str;

    
}

+ (BOOL)isChinesecharacter:(NSString *)string{
    if (string.length == 0) {
        return NO;
    }
    unichar c = [string characterAtIndex:0];
    if (c >=0x4E00 && c <=0x9FA5){
        return YES;//汉字
    } else {
        return NO;//英文
    }
}
//计算汉字的个数
+ (NSInteger)chineseCountOfString:(NSString *)string{
    int ChineseCount = 0;
    if (string.length == 0) {
        return 0;
    }
    for (int i = 0; i<string.length; i++) {
        unichar c = [string characterAtIndex:i];
        if (c >=0x4E00 && c <=0x9FA5){
            ChineseCount++ ;//汉字
        }    }
    return ChineseCount;
}
//计算字母的个数
+ (NSInteger)characterCountOfString:(NSString *)string{
    int characterCount = 0;
    if (string.length == 0) {
        return 0;
    }
    for (int i = 0; i<string.length; i++) {
        unichar c = [string characterAtIndex:i];
        if (c >=0x4E00 && c <=0x9FA5){
        }else{
            characterCount++;//英文
        }
    }
    return characterCount;
}
//获取系统语言
+ (NSString *)getCurrentLanguage
{
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    if (currentLanguage == nil) {
        currentLanguage = @"";
    }
    return currentLanguage;
}
+ (NSString*) uuid {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}
+ (NSString *)deviceIPAdress
{
    NSString *address = @"an error occurred when obtaining ip address";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) { // 0 表示获取成功
        
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    freeifaddrs(interfaces);  
    if(address==nil){
        address= @"";
    }
    return address;
}
+ (NSString *)APPID{
    return @"1.0.1";
}
+ (void)donghuaOfPaoWuXian:(CGFloat)startx stary:(CGFloat)stary endx:(CGFloat)endx endy:(CGFloat)endy superView:(UIView *)fatherView{
    CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    //    复制代码然后设置一个路径：
    CGMutablePathRef thePath = CGPathCreateMutable();
    
    CGPathMoveToPoint(thePath, NULL, startx, stary);
    
    CGPathAddQuadCurveToPoint(thePath, NULL, 150, stary-100, endx, endy);
    //    复制代码注：startPoint是起点，endPoint是终点，150，30是x,y轴的控制点，自行调整数值可以出现理想弧度效果
    
    //    把路径给动画变量，设置个动画时间
    bounceAnimation.path = thePath;
    
    bounceAnimation.duration = 0.7;
    //    复制代码最后把这个动画添加给view的layer
    UIImageView *vie = [[UIImageView alloc]initWithFrame:CGRectMake(-1000, 0, 15, 15)];
    vie.image = [UIImage imageNamed:@"favp"];
    [fatherView bringSubviewToFront:vie];
    [fatherView addSubview:vie];
    [vie.layer addAnimation:bounceAnimation forKey:@"move"];
}

+ (void)lineViewWithHeightofTop:(CGFloat)heihtoftop superView:(UIView *)fatherView spacing:(CGFloat)spacing color:(UIColor *)color lineHeight:(CGFloat)height{
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(spacing, heihtoftop-height, fatherView.bounds.size.width-2*spacing, height)];
    line.backgroundColor = color;
    [fatherView addSubview:line];
}

+ (void)lineViewWithHeightofTop:(CGFloat)heihtoftop superView:(UIView *)fatherView spacing:(CGFloat)spacing image:(UIImage *)imagename lineHeight:(CGFloat)height{
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(spacing, heihtoftop-height, fatherView.bounds.size.width-2*spacing+1000, height)];
    line.backgroundColor = [UIColor colorWithPatternImage:imagename];
    [fatherView addSubview:line];
}

+ (UIView *)newlineViewWithHeightofTop:(CGFloat)heihtoftop superView:(UIView *)fatherView spacing:(CGFloat)spacing color:(UIColor *)color lineHeight:(CGFloat)height{
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(spacing, heihtoftop-height, fatherView.frame.size.width-2*spacing, height)];
    line.backgroundColor = color;
    [fatherView addSubview:line];
    
    return line;
}

+ (void)lineViewWithHeightofTop1:(CGFloat)heihtoftop superView:(UIView *)fatherView spacing:(CGFloat)spacing color:(UIColor *)color lineHeight:(CGFloat)height{
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(spacing, heihtoftop-height, fatherView.bounds.size.width, height)];
    line.backgroundColor = color;
    [fatherView addSubview:line];
}



+ (void)lineViewWithWidthtofLeft:(CGFloat)widthofleft superView:(UIView *)fatherView spacing:(CGFloat)spacing color:(UIColor *)color lineWidth:(CGFloat)width{
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(widthofleft, spacing, width, fatherView.frame.size.height-2*spacing)];
    line.backgroundColor = color;
    [fatherView addSubview:line];
}

//  将数组重复的对象去除，只保留一个
+ (NSArray *)arrayWithMemberIsOnly:(NSArray *)array
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (NSArray *number in array) {
        [dict setObject:number forKey:number];
    }
    NSLog(@"%@",[dict allValues]);
    return [dict allValues];
}
+ (NSArray *)arrayObjectOfStringWithMemberIsOnly:(NSArray *)array
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (NSString *number in array) {
        [dict setObject:number forKey:number];
    }
    NSLog(@"%@",[dict allValues]);
    return [dict allValues];
}

+ (NSString *)arrayTransformStringWithArray:(NSArray *)array{
    NSString *string=@"";
    for (int i = 0; i <array.count; i++) {
        NSString *str = nil;
        if (i == 0) {
            str = array[i];
        }else{
            str = [NSString stringWithFormat:@",%@",array[i]];
        }
        string = [string stringByAppendingString:str];
    }
    return string;
}

/**
 *  渐变色
 */
+(void)jianbianse:(UIView *)view beginColor:(UIColor *)bColor midColor:(UIColor *)mColor endColor:(UIColor *)eColor ByGradientType:(GradientType)gradientType{
    
    CAGradientLayer *gradient = [CAGradientLayer layer];
    
    switch (gradientType) {
        case 0:
            gradient.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
            break;
        case 1:
            gradient.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
            break;
        case 2:
            gradient.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
            break;
        case 3:
            gradient.frame = CGRectMake(view.frame.size.width, 0, view.frame.size.width, view.frame.size.height);
            break;
        default:
            break;
    }
    
    gradient.startPoint = CGPointMake(0, 0);
    gradient.endPoint = CGPointMake(1.0, 0);
    
    gradient.colors = [NSArray arrayWithObjects:
                       
                       (id)bColor.CGColor,
                       
                       (id)mColor.CGColor,
                       
                       (id)eColor.CGColor,
                       
                       nil];
    
//    [view.layer insertSublayer:gradient atIndex:0];
    [view.layer addSublayer:gradient];
}
+ (void) viewImageFromColors:(NSArray*)colors ByGradientType:(GradientType)gradientType view:(UIView *)vi{
    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(vi.frame.size, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    CGPoint start;
    CGPoint end;
    switch (gradientType) {
        case 0:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(0.0, vi.frame.size.height);
            break;
        case 1:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(1.0, 0.0);
            break;
        case 2:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(vi.frame.size.width, vi.frame.size.height);
            break;
        case 3:
            start = CGPointMake(vi.frame.size.width, 0.0);
            end = CGPointMake(0.0, vi.frame.size.height);
            break;
        default:
            break;
    }
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    vi.backgroundColor = [UIColor colorWithPatternImage:image];
}


+ (NSString *)colorAtPixel:(CGPoint)point imageView:(UIImageView *)imageV{
    
    // Cancel if point is outside image coordinates
    
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, imageV.frame.size.width, imageV.frame.size.height), point)) {
        
        return nil;
        
    }
    
    
    NSInteger pointX = trunc(point.x);
    
    NSInteger pointY = trunc(point.y);
    
    CGImageRef cgImage = imageV.image.CGImage;
    
    NSUInteger width = imageV.frame.size.width;
    
    NSUInteger height = imageV.frame.size.height;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    int bytesPerPixel = 4;
    
    int bytesPerRow = bytesPerPixel * 1;
    
    NSUInteger bitsPerComponent = 8;
    
    unsigned char pixelData[4] = { 0, 0, 0, 0 };
    
    CGContextRef context = CGBitmapContextCreate(pixelData,
                                                 
                                                 1,
                                                 
                                                 1,
                                                 
                                                 bitsPerComponent,
                                                 
                                                 bytesPerRow,
                                                 
                                                 colorSpace,
                                                 
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    
    CGColorSpaceRelease(colorSpace);
    
    CGContextSetBlendMode(context, kCGBlendModeCopy);
    
    
    // Draw the pixel we are interested in onto the bitmap context
    
    CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height);
    
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
    
    CGContextRelease(context);
    
    // Convert color values [0..255] to floats [0.0..1.0]
    
    CGFloat red = (CGFloat)pixelData[0] ;
    
    CGFloat green = (CGFloat)pixelData[1] ;
    
    CGFloat blue = (CGFloat)pixelData[2] ;
    
//    CGFloat alpha = (CGFloat)pixelData[3];
    
    return [NSString stringWithFormat:@"%.f%.f%.f",red,green,blue];
    
}

+ (void)jianbianAnimoWithDelegate:(id)obj addView:(UIView *)views{
    
    views.backgroundColor = [UIColor colorWithRed:172/255.0 green:134/255.0 blue:171/255.0 alpha:1];
    [df layerWithView:views radius:views.frame.size.width/2 width:0 color:nil];
    CABasicAnimation * animation=[CABasicAnimation  animationWithKeyPath:@"opacity"];
    //设置透明度最小值
    [animation setFromValue:[NSNumber numberWithFloat:0.0]];
    //设置透明度最大值
    [animation setToValue:[NSNumber numberWithInt:1.0]];
    //播放速率
    [animation setDuration:.1];
    //播放次数
    [animation setRepeatCount:0];
    //设置监听代理
    [animation setDelegate:obj];
    [animation setAutoreverses:NO];//默认的是NO，即透明完毕后立马恢复，YES是延迟恢复
    [views.layer  addAnimation:animation forKey:@"img-opacity"];

}


+(void)fanzhuanAnimoAddView:(UIView *)views{
    CATransition *animation = [CATransition animation];
    animation.type =@"oglFlip";
    [animation setDuration:1.3];
    [animation setRepeatCount:1.0];
    [animation setDelegate:self];
    [animation setSubtype:@"fromRight"];
    [views.layer addAnimation:animation forKey:@"s oglFlip"];

}


+ (void)getImageView:(UIView *)fatherV isbigImaga:(NSString *)ishave{
    CGFloat x = fatherV.frame.size.width;
    CGFloat y = fatherV.frame.size.height;
    BOOL isH = NO;
    NSArray *arr = [fatherV subviews];
    for (UIView *view in arr) {
        if (view.tag == 6025638) {
            isH = YES;
        }
    }

    if (ishave != nil && !isH) {
        UIView *back = [[UIView alloc]initWithFrame:CGRectMake(0,0,x,y)];
        back.tag = 6025638;
        [fatherV addSubview:back];
//        back.backgroundColor = RGBACOLOR(100, 100, 100, .5);
        CGFloat images = 200;
        UIImageView *imageV1= [[UIImageView alloc]initWithFrame:CGRectMake((KSCREENWidth-images)/2, (KSCREENHeight-images)/2-KagainChangeHeight, 200, 200)];
        imageV1.image  = [UIImage imageNamed:@"tip2"];
        [back addSubview:imageV1];

    }
}

+ (void)removeImageView:(UIView *)fatherV{
    NSArray *arr = [fatherV subviews];
    for (UIView *view in arr) {
        if (view.tag ==6025637 || view.tag == 6025638) {
            [view removeFromSuperview];
        }
    }
}


/**
*  生成二维码
*/
+ (CIImage *)createQRForString:(NSString *)qrString {
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
    // 创建filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 设置内容和纠错级别
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    // 返回CIImage
    return qrFilter.outputImage;
}
//因为生成的二维码是一个CIImage，我们直接转换成UIImage的话大小不好控制，所以使用下面方法返回需要大小的UIImage：
+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

/**
 *  shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
 */
+(void)setTheViewYiYing:(UIView *)vi shadowColor:(UIColor *)color shadowOffset:(CGSize)ssize apla:(CGFloat)apl{
    //加阴影
    vi.layer.masksToBounds = YES;
//    vi.clipsToBounds = NO;
    vi.layer.shadowColor = color.CGColor;//shadowColor阴影颜色
    vi.layer.shadowOffset = ssize;//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
//    vi.layer.shadowRadius = 5;
    vi.layer.shadowOpacity = apl;//阴影透明度，默认0
 
}


 /**
*  清理缓存
*/
+(float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

+(float)folderSizeAtPath{
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager=[NSFileManager defaultManager];
    float folderSize = 0.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            folderSize +=[df fileSizeAtPath:absolutePath];
        }
        //SDWebImage框架自身计算缓存的实现
        //folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
        
        return folderSize;
    }
    return 0;
}

+(void)clearCache{
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    //[[SDImageCache sharedImageCache] cleanDisk];
    [df showAlertWithTitle:@"缓存已清理" message:nil btn1:@"确定" btn2:nil btn3:nil delegate:nil tag:0];
}


+ (UIView *)showTongZhi:(NSString *)title father:(UIView *)father{
    UIView *vie = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWidth, 50)];
    vie.backgroundColor = [UIColor blackColor];
    UIImageView *imgv = [[UIImageView alloc]initWithFrame:CGRectMake(KSCREENWidth/4, 20, 20, 20)];
    imgv.image = [UIImage imageNamed:@"180"];
    [vie addSubview:imgv];
    [df layerWithView:imgv radius:4 width:0 color:nil];
    UILabel *labe = [[UILabel alloc]initWithFrame:CGRectMake(imgv.frame.size.width +imgv.frame.origin.x +20, 20, KSCREENWidth-40-(imgv.frame.size.width +imgv.frame.origin.x +20), 20)];
    labe.text = title;
    labe.font = [UIFont systemFontOfSize:12];
    labe.textColor = [UIColor whiteColor];
    [vie addSubview:labe];
    [father addSubview:vie];
    return vie;
}

+ (NSString *)getString:(id)recevicer{
    
    return [NSString stringWithFormat:@"%@",recevicer];
}

+ (NSString *)getintToString:(NSInteger)recevicer{
    
    return [NSString stringWithFormat:@"%ld",(long)recevicer];
}

+ (UIViewController*)viewController:(UIView *)view{
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

#pragma mark  showBigImageV
+ (UIView *)getBigImageViewWithImageURL:(NSString *)url{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWidth, KSCREENHeight)];
    view.tag =  98984598;
    view.backgroundColor = [UIColor blackColor];
    [[JTCSMSingle shareSingle].theWindow addSubview:view];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWidth, KSCREENHeight/2)];
    imageView.userInteractionEnabled = YES;
    [view addSubview:imageView];
//    
//    [SDWebImageManager.sharedManager downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//        imageView.frame = CGRectMake(0, 0, KSCREENWidth, KSCREENWidth/image.size.width*image.size.height);
//        imageView.center = view.center;
//        imageView.image = image;
//        
//    }];
    return view;
}

//转换成当前时刻

+ (NSString *)timeFormatted:(int)totalSeconds

{
    NSDate  *date = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"MM-dd HH:mm"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:localeDate];
    //输出格式为：2010-10-27 10:22:13
    //alloc后对不使用的对象别忘了release
    return currentDateStr;
}



//*prame mark
//弹出键盘 改变cell 位置
//*
+ (void)changeCellPointwithKeyboardHeight:(CGFloat)keyboardH touchTextfield:(id)textfield tabelView:(UITableView *)tabelView{
    
    UIView *view = textfield;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardH, 0.0);
    tabelView.scrollEnabled = YES;
    tabelView.contentInset = contentInsets;
    tabelView.scrollIndicatorInsets = contentInsets;
    NSLog(@"keyboardWasShown");
    CGRect aRect =[tabelView superview].frame;
    aRect.size.height -= keyboardH;
    if (!CGRectContainsPoint(aRect, view.superview.superview.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, ([view isKindOfClass:[UITextField class]])?view.superview.superview.frame.origin.y-aRect.size.height+44:view.superview.superview.superview.frame.origin.y-aRect.size.height+104);
        [tabelView setContentOffset:scrollPoint animated:YES];
    }

}

+ (BOOL)isLogin{
    
    if ([KTokenString isEqualToString:@""]) {
        
        [df showAlertWithTitle:@"您还没有登录，请登录" message:@"" btn1:@"确定" btn2:@"返回" btn3:nil delegate:[JTCSMSingle shareSingle].thevc tag:100];
        return NO;
    }
    return YES;
}

+(UIImage*) createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

+(CGFloat)getSpaceLabelLineSpacing:(CGFloat)spacing withFont:(UIFont*)font withLabel:(UILabel *)label {
    
    label.numberOfLines = 0;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:spacing];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
    label.attributedText = attributedString;
    [label sizeToFit];
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = spacing;
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
                          };
    
    CGSize size = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}
@end
